package com.mc.web.controller.gpm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.mc.clt.domain.CltInfo;
import com.mc.common.constant.Constants;
import com.mc.common.core.domain.model.LoginUser;
import com.mc.common.core.page.TableDataInfo;
import com.mc.common.utils.ServletUtils;
import com.mc.framework.web.service.TokenService;
import com.mc.gpm.domain.GpmShelveStatistics;
import com.mc.gpm.domain.GpmStorage;
import com.mc.gpm.service.IGpmStorageService;
import com.mc.web.controller.common.CommonController;
import org.apache.xmlbeans.impl.tool.XMLBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mc.common.annotation.Log;
import com.mc.common.core.controller.BaseController;
import com.mc.common.core.domain.AjaxResult;
import com.mc.common.enums.BusinessType;
import com.mc.gpm.domain.GpmShelve;
import com.mc.gpm.service.IGpmShelveService;
import com.mc.common.utils.poi.ExcelUtil;
import org.springframework.web.client.RestTemplate;

/**
 * 货架Controller
 *
 * @author mc
 * @date 2021-03-18
 */
@RestController
@RequestMapping("/gpm/shelve")
public class GpmShelveController extends BaseController
{
    @Autowired
    private IGpmShelveService gpmShelveService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IGpmStorageService storageService;
//
//    private LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

    private static final Logger log = LoggerFactory.getLogger(GpmShelveController.class);

    /**
     * 查询货架列表
     */
    @PreAuthorize("@ss.hasPermi('gpm:shelve:list')")
    @GetMapping("/list")
    public AjaxResult list(GpmShelve gpmShelve)
    {
        List<GpmShelve> list = gpmShelveService.selectGpmShelveList(gpmShelve);
        return AjaxResult.success(list);
    }
    /**
     * 查询种质资源入库列表
     */
    @PreAuthorize("@ss.hasPermi('gpm:storage:list')")
    @GetMapping("/statistical")
    public TableDataInfo statisticalList(GpmShelve gpmShelve)
    {
        List<GpmShelveStatistics> statisticsList = new ArrayList<GpmShelveStatistics>();
        startPage();
        List<GpmShelve> list = gpmShelveService.selectGpmShelveList(gpmShelve);
        GpmStorage gpmStorage = new GpmStorage();
        gpmStorage.setShelveId(gpmShelve.getParentId().intValue());
        //List<GpmShelve> list = gpmShelveService.selectGpmShelveListByNo(gpmShelve.getId());
        if(list.size() == 0){
            startPage();
            gpmStorage.setStatus("0");
            return getDataTable(storageService.selectGpmStorageList(gpmStorage));
        }else{
            int order = 1; //序号
            String name; //名称
            String place; //所属位置
            int gerCount; //种质数量
            int sonCount;//子类数量
            int counterCount;//货柜数量
            int shelvesCount;//货架数量
            Date createTime; //创建时间
            for(GpmShelve shelve : list){

                GpmShelveStatistics gpmShelveStatistics = new GpmShelveStatistics();
                gpmShelveStatistics.setOrder(order);
                gpmShelveStatistics.setName(shelve.getName());
                gpmShelveStatistics.setNickName(shelve.getNickName());
                gpmShelveStatistics.setPlace(shelve.getPlaceName());
                shelve.setType("");
                shelve.setParentId(shelve.getId());
                gpmShelveStatistics.setSonCount(gpmShelveService.selectGpmShelveListByNo(shelve));
                gpmStorage.setShelveId(gpmShelve.getParentId().intValue());
                gpmShelveStatistics.setCounterCount(storageService.countGpmStorageByShelveNumber(shelve.getNumber()));
                shelve.setParentId(null);
                shelve.setType("5");
                gpmShelveStatistics.setShelvesCount(gpmShelveService.selectGpmShelveListByNo(shelve));
                shelve.setType("4");
                gpmShelveStatistics.setGerCount(gpmShelveService.selectGpmShelveListByNo(shelve));
                gpmShelveStatistics.setCreateTime(shelve.getCreateTime());
                statisticsList.add(gpmShelveStatistics);
                order++;
            }
            return getDataTable(statisticsList,gpmShelveService.selectGpmShelveList(gpmShelve).size());
        }


    }
    /**
     * 导出货架列表
     */
    @PreAuthorize("@ss.hasPermi('gpm:shelve:export')")
    @Log(title = "货架", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(GpmShelve gpmShelve)
    {
        List<GpmShelve> list = gpmShelveService.selectGpmShelveList(gpmShelve);
        ExcelUtil<GpmShelve> util = new ExcelUtil<GpmShelve>(GpmShelve.class);
        return util.exportExcel(list, "shelve");
    }

    /**
     * 获取货架详细信息
     */
    @PreAuthorize("@ss.hasPermi('gpm:shelve:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(gpmShelveService.selectGpmShelveById(id));
    }

    /**
     * 新增货架
     */
    @PreAuthorize("@ss.hasPermi('gpm:shelve:add')")
    @Log(title = "新增货架", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GpmShelve gpmShelve)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        gpmShelve.setState("0");
        gpmShelve.setCreateUserId(loginUser.getUsername());
        gpmShelveService.insertGpmShelve(gpmShelve);
        GpmShelve parentGpmShelve = gpmShelveService.selectGpmShelveById(gpmShelve.getParentId());
        if(parentGpmShelve==null){
            gpmShelve.setPlaceName(gpmShelve.getName());
            gpmShelve.setNumber(String.valueOf(gpmShelve.getId()));
        }else{
            gpmShelve.setPlaceName(parentGpmShelve.getPlaceName()+"-"+gpmShelve.getName());
            gpmShelve.setNumber(parentGpmShelve.getNumber()+"-"+gpmShelve.getId());
        }


        gpmShelveService.updateGpmShelve(gpmShelve);
        if(gpmShelve.getType()!=null && gpmShelve.getType().equals("1")){
            gpmShelve.setObjectId(restTemplate(gpmShelve,"addFeatures"));
        }
        return AjaxResult.success(gpmShelveService.selectGpmShelveById(gpmShelve.getId()));
    }

    /**
     * 修改货架
     */
    @PreAuthorize("@ss.hasPermi('gpm:shelve:edit')")
    @Log(title = "修改货架", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GpmShelve gpmShelve)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        gpmShelve.setUpdateUserId(loginUser.getUsername());
        gpmShelveService.updateGpmShelve(gpmShelve);
        GpmShelve gpmShelve1 = gpmShelveService.selectGpmShelveById(gpmShelve.getId());
        if(gpmShelve1.getType()!=null && gpmShelve1.getType().equals("1")){
            gpmShelve.setObjectId(restTemplate(gpmShelve1,"updateFeatures"));
        }

        return AjaxResult.success(gpmShelveService.selectGpmShelveById(gpmShelve.getId()));
    }

    /**
     * 删除货架
     */
    @PreAuthorize("@ss.hasPermi('gpm:shelve:remove')")
    @Log(title = "货架", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable long id)
    {
        GpmShelve gpmShelve = new GpmShelve();
        gpmShelve = gpmShelveService.selectGpmShelveById(id);
        if(gpmShelve.getType()!=null && gpmShelve.getType().equals("1")){
            gpmShelve.setObjectId(restTemplate(gpmShelve,"deleteFeatures"));
        }
        return toAjax(gpmShelveService.deleteGpmShelveById(gpmShelve.getNumber()));
    }

    public String restTemplate(GpmShelve gpmShelve, String action){
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("f","pjson");
        params.add("frollbackOnFailure", "true");
        String cltTime = null;

        if(action.equals("addFeatures")){
            params.add("features", "[{\"attributes\": {\n" +
                    "    \"NAME\": \""+gpmShelve.getName()+"\",\n" +
                    "    \"CODE\": \""+gpmShelve.getId()+"\"\n" +
                    "   },\n" +
                    "   \"geometry\": {\n" +
                    "    \"x\": "+gpmShelve.getX()+",\n" +
                    "    \"y\": "+gpmShelve.getY()+"\n" +
                    "   }}]");
        }else if(action.equals("updateFeatures")){
            params.add("features", "[{\"attributes\": {\n" +
                    "    \"OBJECTID\": "+selectObjectId(String.valueOf(gpmShelve.getId()))+",\n" +
                    "    \"NAME\": \""+gpmShelve.getName()+"\"\n" +
                    "   },\n" +
                    "   \"geometry\": {\n" +
                    "    \"x\": "+gpmShelve.getX()+",\n" +
                    "    \"y\": "+gpmShelve.getY()+"\n" +
                    "   }}]");
        }else{
            params.add("objectIds", selectObjectId(String.valueOf(gpmShelve.getId())));
        }
        log.info(params.toString());
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, null);
        ResponseEntity<String> response = restTemplate.postForEntity(
                Constants.GIS_SERVER_URL1+action,
                requestEntity,
                String .class);
        String jsonObject = response.getBody();
        log.info(jsonObject);
        if(action.equals("addFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("addResults").getJSONObject(0).getString("objectId");
        }else if(action.equals("updateFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("updateResults").getJSONObject(0).getString("objectId");
        }else{
            return JSONObject.parseObject(jsonObject).getJSONArray("deleteResults").getJSONObject(0).getString("objectId");
        }

    }

    public  String selectObjectId(String code){
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("where","code = \""+code+"\"");
        params.add("geometryType","esriGeometryEnvelope");
        params.add("spatialRel","esriSpatialRelIntersects");
        params.add("units","esriSRUnit_Foot");
        params.add("outFields","OBJECTID");
        params.add("returnGeometry","false");

        params.add("returnDistinctValues","false");
        params.add("returnIdsOnly","false");
        params.add("returnCountOnly","false");
        params.add("returnExtentOnly","false");
        params.add("returnZ","false");
        params.add("returnM","false");
        params.add("multipatchOption","xyFootprint");
        params.add("returnTrueCurves","false");
        params.add("returnExceededLimitFeatures","false");
        params.add("returnCentroid","false");
        params.add("sqlFormat","none");
        params.add("featureEncoding","esriDefault");
        params.add("f","pjson");



        String body = null;
        try {
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, null);

            ResponseEntity<String> forEntity = restTemplate.postForEntity(Constants.GIS_SERVER_URL1+"query", requestEntity, String.class);
            body = forEntity.getBody();
        } catch (Exception e) {
        }
        return JSONObject.parseObject(body).getJSONArray("features").getJSONObject(0).getJSONObject("attributes").getString("OBJECTID");
    }
}